package com.mming.sso.service.Impl;

import com.mming.sso.bean.UserInfo;
import com.mming.sso.dao.UserRepo;
import com.mming.sso.entity.User;
import com.mming.sso.service.UserService;
import com.mming.sso.util.SaltUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepo userRepo;

    private static final short AVAILABLE_STATE = 1;

    private static final short UNAVAILABE_STATE = 0;

    @Override
    @Transactional
    public UserInfo getUserInfoByUsername(String username) {
        if (!userRepo.existsUserByUsernameAndState(username, AVAILABLE_STATE)) {
            return null;
        } else {
            User user = userRepo.findByUsernameAndState(username, AVAILABLE_STATE);
            return new UserInfo(user);
        }
    }

    @Transactional
    public boolean login(String username, String password, String IP) {
        if (userRepo.existsUserByUsernameAndState(username, AVAILABLE_STATE)) {
            User user = userRepo.findByUsernameAndState(username, AVAILABLE_STATE);
            String encryptedPassword = DigestUtils.md5Hex(user.getSalt() + "." + DigestUtils.md5Hex(password));
            boolean loginResult = user.getPassword().equals(encryptedPassword);
            //TODO bug fix 没有正确更正上次登录ip
            if (loginResult && IP != null) {
                user.setLastLoginIp(IP);
                userRepo.save(user);
            }
            return loginResult;
        } else {
            return false;
        }
    }

    @Transactional
    public int register(User addingUser) {
        boolean existInUsers = userRepo.existsUserByUsernameAndState(
                addingUser.getUsername(), AVAILABLE_STATE);

        if (!existInUsers) {
            String salt = SaltUtil.getSalt();
            String encryptedPassword = DigestUtils.md5Hex(salt + "." +
                    DigestUtils.md5Hex(addingUser.getPassword()));

            addingUser.setPassword(encryptedPassword);
            addingUser.setSalt(salt);
            addingUser.setState(AVAILABLE_STATE);

            log.info(addingUser.getUsername() + " registered success");
            return userRepo.save(addingUser).getId();
        } else
            return -1;
    }

    @Transactional
    public int banUser(String username) {
        if (userRepo.existsUserByUsernameAndState(username, AVAILABLE_STATE)) {
            return userRepo.deleteUserInLogical(username);
        } else
            return -1;
    }
}
